package com.geez.bbl.projector;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;

/**
 * The Class CreateJarFile.
 */
public class CreateJarFile {

	/** The BUFFE r_ size. */
	public static int BUFFER_SIZE = 10240;

	/**
	 * Creates the jar archive.
	 *
	 * @param archiveFile the archive file
	 * @param tobeJared the tobe jared
	 */
	public static void createJarArchive(File archiveFile,
			ArrayList<File> tobeJared) {
		try {
			byte buffer[] = new byte[BUFFER_SIZE];
			// Open archive file
			FileOutputStream stream = new FileOutputStream(archiveFile);
			JarOutputStream out = new JarOutputStream(stream);

			for (int i = 0; i < tobeJared.size(); i++) {
				if (tobeJared.get(i) == null || !tobeJared.get(i).exists())
					// || tobeJared.get(i).isDirectory())
					continue; // Just in case...


				// Add archive entry
				if (tobeJared.get(i).isDirectory()) {
					//System.out.println("Adding Directory: " + tobeJared.get(i).getName());
					JarEntry jarAdd = new JarEntry(tobeJared.get(i).getPath()
							+ "/");
					jarAdd.setTime(tobeJared.get(i).lastModified());
					out.putNextEntry(jarAdd);
					continue;
				} else {
					//System.out.println("Adding File: " + tobeJared.get(i).getName());
					//System.out.println(tobeJared.get(i).getPath());
					JarEntry jarAdd = new JarEntry(tobeJared.get(i).getPath());
					jarAdd.setTime(tobeJared.get(i).lastModified());
					out.putNextEntry(jarAdd);
				}
				// Write file to archive
				FileInputStream in = new FileInputStream(tobeJared.get(i));
				while (true) {
					int nRead = in.read(buffer, 0, buffer.length);
					if (nRead <= 0)
						break;
					out.write(buffer, 0, nRead);
				}
				in.close();
			}

			out.close();
			stream.close();
			System.out.println("Adding completed OK");
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("Error: " + ex.getMessage());
		}
	}
}